<template>
  <div class="custom-tree-container">
    <Sticky :class-name="'sub-navbar'">
      <el-button
        v-loading="loading"
        type="success"
        is-add
        @click="handleAdd"
      >
        新增课程计划
      </el-button>
    </Sticky>
    <el-dialog :title="operation?'新增':'编辑'" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="上级节点" :label-width="formLabelWidth">
          <el-select v-model="form.upperId" placeholder="请选择上级节点">
            <el-option v-for="(upper,i) in upperList" :key="i" :label="upper.name" :value="upper.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off" />
        </el-form-item>
        <el-form-item label="类型" :label-width="formLabelWidth">
          <el-radio v-model="form.type" label="0">无</el-radio>
          <el-radio v-model="form.type" label="1">文档</el-radio>
          <el-radio v-model="form.type" label="2">视频</el-radio>
        </el-form-item>
        <el-form-item label="层级" :label-width="formLabelWidth">
          <el-radio v-model="form.grade" label="2">章节</el-radio>
          <el-radio v-model="form.grade" label="3">课时</el-radio>
        </el-form-item>
        <el-form-item label="时长，分钟：秒" :label-width="formLabelWidth">
          <el-input v-model="form.timelength" autocomplete="off" />
        </el-form-item>
        <el-form-item label="排序字段(数字越大，排序靠后)" :label-width="formLabelWidth">
          <el-input v-model="form.orderBy" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addTeachplan">确 定</el-button>
      </div>
    </el-dialog>
    <el-alert
      title="温馨提示：创建了课时最好选择资源，课程测试章节不需要选择资源，发布的作业尽量不要修改，有需要请联系管理员"
      type="warning"
      effect="dark"
      size="mini"
    />
    <div class="block">
      <el-tree
        :data="teachData"
        node-key="id"
        default-expand-all
        :expand-on-click-node="false"
      >
        <span slot-scope="{ node }" class="custom-tree-node">
          <span>{{ node.label }}</span>
          <div v-show="node.data.type!=0">
            <el-tag size="mini" :type="node.data.type==1?'warning':'success'">{{ node.data.type==1?'文档':'视频' }}</el-tag>
          </div>

          <span>
            <el-button
              v-if="!node.label.indexOf('课时')"
              type="text"
              size="mini"
              @click="chooseResource(node)"
            >
              选择资源
            </el-button>
            <el-dialog title="选择资源" :visible.sync="dialogResourceVisible">
              <el-form :model="resourceForm">
                <el-form-item label="选择资源" :label-width="formLabelWidth">
                  <el-select v-model="resourceForm.resourceId" placeholder="请选择资源">
                    <el-option v-for="(resource,i) in resourceList" :key="i" :label="resource.name" :value="resource.id" />
                  </el-select>
                </el-form-item>
                <div style="margin: 10px 200px">
                  <el-button @click="dialogResourceVisible = false">取 消</el-button>
                  <el-button type="primary" @click="commitChoose">确 定</el-button>
                  <!-- </div> -->
                </div></el-form>
            </el-dialog>
            <el-button
              v-if="!node.label.indexOf('课时')"
              type="text"
              size="mini"
              @click="taskPublish(node)"
            >
              作业发布
            </el-button>
            <el-dialog title="作业发布" width="80%" :visible.sync="dialogTaskVisible">
              <el-alert
                title="作业的选择题最多5题，测验的选择题最多20题，操作题最多1题，有需求找管理员！！！！！！！！！！"
                type="warning"
                effect="dark"
                size="medium"
              />
              <div style="text-align: center">
                <el-transfer
                  v-model="value"
                  style="text-align: left; display: inline-block ;"
                  filterable
                  :left-default-checked="[2, 3]"
                  :right-default-checked="[1]"
                  :titles="['题目列表', '选中']"
                  :format="{
                    noChecked: '${total}',
                    hasChecked: '${checked}/${total}'
                  }"
                  :data="data"
                  @change="handleChange"
                >
                  <span slot-scope="{ option }">{{ option.key }} - {{ option.label }}</span>
                  <el-button
                    slot="right-footer"
                    class="transfer-footer"
                    size="middle"
                    @click="addTasks"
                  >确认</el-button>
                </el-transfer>
              </div>
            </el-dialog>
            <el-button
              v-if="!node.label.indexOf('课时')"
              type="text"
              size="mini"
              @click="() => taskmanage(node)"
            >
              作业批改
            </el-button>
            <el-button
              v-if="node.label.indexOf('课程')"
              type="text"
              size="mini"
              @click="handleEdit(node)"
            >
              编辑
            </el-button>
            <el-button
              v-if="node.label.indexOf('课程')"
              type="text"
              size="mini"
              @click="deleteData(node)"
            >
              删除
            </el-button>
          </span>
        </span>
      </el-tree>
    </div>
  </div>
</template>

<script>
import Sticky from '@/components/Sticky'
import { createTeachPlan, getUpperList, getTeachplan, getResourceList, chooseResource, deleteTeachplan } from '@/api/teachplan'
import { getAllProblem } from '@/api/problem'
import { addTask } from '@/api/task'
export default {
  inject: ['reload'],
  components: {
    Sticky
  },
  data() {
    const teachData = [{
      id: 1,
      label: '课程:暂无',
      type: '0',
      children: []
    }]
    return {
      teachData: JSON.parse(JSON.stringify(teachData)),
      loading: false,
      dialogFormVisible: false,
      dialogResourceVisible: false,
      dialogTaskVisible: false,
      operation: false,
      teachplanId: '',
      form: {
        id: '',
        name: '',
        upperId: '',
        type: '无',
        grade: '',
        timelength: '',
        orderBy: ''
      },
      upperList: [],
      resourceList: [],
      resourceForm: {
        teachplanId: '',
        resourceId: ''
      },
      formLabelWidth: '120px',
      data: [],
      studentList: [],
      value: [],
      renderFunc(h, option) {
        return <span>{ option.key } - { option.label }</span>
      }
    }
  },
  beforeCreate() {
    getTeachplan().then(response => {
      console.log(response.data)
      this.teachData = response.data
    })
  },
  methods: {
    addTeachplan() {
      // 创建课程计划
      const form = Object.assign({}, this.form)
      createTeachPlan(form).then(response => {
        this.$message({
          type: 'success',
          message: '创建成功'
        })
        this.reload()
        this.dialogFormVisible = false
      }).catch(response => {
        this.$message({
          type: 'error',
          message: '创建失败'
        })
      })
    },
    chooseResource(node) {
      this.resourceForm.teachplanId = node.key
      this.dialogResourceVisible = true
      getResourceList().then(response => {
        console.log(response.data)
        this.resourceList = response.data
      })
    },
    commitChoose() {
      const form = Object.assign({}, this.resourceForm)
      chooseResource(form).then(response => {
        this.$message({
          type: 'success',
          message: '添加成功'
        })
        this.dialogResourceVisible = false
      }).catch(response => {
        this.$message({
          type: 'error',
          message: '添加失败'
        })
      })
    },
    taskPublish(node) {
      this.teachplanId = node.data.id
      this.dialogTaskVisible = true
      getAllProblem().then(response => {
        console.log(response.data)
        this.studentList = response.data
        const data = []
        for (let i = 0; i < this.studentList.length; i++) {
          data.push({
            key: this.studentList[i].id,
            label: this.studentList[i].pname,
            nickName: this.studentList[i].ptype
          })
        }
        this.data = data
      })
    },
    taskmanage(node, data) {
      this.$router.push({ path: '/course/task', query: { teachplanId: node.data.id }})
    },
    // 显示编辑界面
    handleEdit: function(node) {
      this.dialogFormVisible = true
      this.operation = false
      getUpperList().then(response => {
        console.log(response.data)
        this.upperList = response.data
      })
      this.form.id = node.data.id
      this.form.upperId = node.parent.data.id
      this.form.name = node.data.label
      this.form.type = node.data.type
      this.form.grade = node.data.grade
      this.form.timelength = node.data.timelength
      this.form.orderBy = node.data.orderBy
    },
    // 显示新增界面
    handleAdd: function() {
      this.dialogFormVisible = true
      this.operation = true
      this.form = {
        name: '',
        upperId: '',
        type: '无',
        grade: '',
        timelength: '',
        orderBy: ''
      }
      getUpperList().then(response => {
        console.log(response.data)
        this.upperList = response.data
      })
    },
    handleChange(value, direction, movedKeys) {
      console.log(value, direction, movedKeys)
    },
    addTasks() {
      // 发送请求
      // console.log(this.value)
      addTask(this.value, this.teachplanId).then(response => {
        this.dialogTaskVisible = false
        this.reload()
        this.$message({
          type: 'success',
          message: '添加成功!'
        })
      }).catch(response => {
        this.$message({
          type: 'error',
          message: '添加失败！'
        })
      })
    },
    deleteData(node) {
      this.$confirm('此操作将永久删除该计划, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTeachplan(node.data.id, node.data.grade).then(response => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.reload()
        }).catch(response => {
          this.$message({
            type: 'error',
            message: '删除失败'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    }
  }
}
</script>

<style>
.custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
}
.el-transfer-panel{
  width: 440px;
}
</style>
